package com.example.xungeng2.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.xungeng2.common.Result;
import com.example.xungeng2.pojo.*;
import com.example.xungeng2.service.TaskPointService;
import com.example.xungeng2.service.UserService;
import com.example.xungeng2.service.XgpqService;
import com.example.xungeng2.unknow.TableMap;
import com.example.xungeng2.util.FileUtil;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Value("${patrol.path}")
    private String uploadPath;
    @Autowired
    private UserService userService;

    @Autowired
    private TaskPointService taskPointService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private XgpqService xgpqService;

    @PostMapping("/login")
    public Result<String> login(@RequestParam("username") String username,
                                @RequestParam("password") String password,
                                HttpServletRequest request){

        User user = null;
        User user1 = new User();
        if (StringUtil.isNullOrEmpty(username) || StringUtil.isNullOrEmpty(password)) {
            return Result.fail("用户名或者密码不能为空");
        }

         user = userService.getUserInformation(username);
        if(user == null){
            return Result.fail("登陆失败");
        }
        user1.setPassword(password);
        user1.setUsername(username);
        boolean flag = userService.pipei(user1);

        if(flag){
            request.getSession().setAttribute("user",user.getUserId());
            return Result.ok("登陆成功");
        }else {
            return Result.fail("登陆失败");
        }
    }
    @RequestMapping("/loginSocket")
    public ResultSocket login(UserSocket user, HttpSession session) {
        ResultSocket result = new ResultSocket();
        User user2 = new User();
        User user1 = userService.getUserInformation(user.getUsername());
        if(user1 == null){
            result.setFlag(false);
            result.setMessage("登陆失败");
            return result;
        }
        user2.setPassword(user.getPassword());
        user2.setUsername(user.getUsername());
        boolean pipei = userService.pipei(user2);
        if(pipei){
            result.setFlag(true);
            //将数据存储到session对象中
            session.setAttribute("user",user.getUsername());
        } else{
            result.setFlag(false);
            result.setMessage("登陆失败");
        }
        return result;

    }

    @RequestMapping("/getUsername")
    public String getUsername(HttpSession session) {
        String username = (String) session.getAttribute("user");
        return username;
    }

    @PostMapping("/register")
    public Result<String> register(@RequestParam("username") String username,
                           @RequestParam("password") String password) {

        // 判断username是否为空，该方法为空返回true
        if (StringUtil.isNullOrEmpty(username) || StringUtil.isNullOrEmpty(password)) {
            return Result.fail("用户名或者密码不能为空");
        }
        boolean b = userService.registerAdminUser(username, password);
        return b ? Result.ok("注册成功") : Result.fail("注册失败");
    }
    @PutMapping("/setUserInformation")
    public Result getAdminUser(User user) {
        // String username = (String) request.getSession().getAttribute("LoginUser");
        String username = user.getUsername();
        boolean b = userService.setUserInformation(user);
        if (b) {
            return Result.ok();
        }
        return Result.fail();
    }

    @PostMapping("/getUserImage")
    public Result fileUpload(@RequestParam("file") MultipartFile multipartFile,
                             @RequestParam("username") String username) {

        if (StringUtil.isNullOrEmpty(username)) {
            return Result.fail("文件名不能为空！");
        }

        if (multipartFile == null) {
            return Result.fail("未选择要上传的文件");
        }

        FileUtil fu = new FileUtil();
        // 获取图片的名字, 使用UUID重命名文件
        String fileName = UUID.randomUUID().toString().replace("-", "") + "." + fu.getSuffix(multipartFile.getOriginalFilename());
        if (!multipartFile.isEmpty()) {
            //获取项目classes/static的地址
            String staticPath = ClassUtils.getDefaultClassLoader().getResource("static").getPath();
            // 图片存储目录
            String url_path = "head/";
            //图片保存路径目录
            String savePath = staticPath + "/" + url_path;
            System.out.println("图片保存地址：" + savePath + fileName);
            // 访问路径=静态资源路径+文件目录路径
            String visitPath = "static/" + url_path;
            System.out.println("图片访问uri：" + visitPath + fileName);
            // 文件夹地址 + 名字 = 图片的路径
            String fileAddress = url_path + fileName;
            try {
                // 把图片前端访问静态路径head/...写入数据库
                User user = new User();
                user.setImg(fileAddress);
                user.setUsername(username);
                boolean b = userService.headerImageUpload(user, staticPath);
                if (b) {
                    // 图片上传的工具类
                    // 参数一：图片的编码格式的字节数组
                    // 参数二：图片存放的文件夹地址
                    // 参数三：图片的名字
                    FileUtil.uploadFile(multipartFile.getBytes(), savePath, fileName);
                    return Result.ok();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Result.fail();
    }


    @GetMapping("/selectUserByUserName/{username}")
    public Result selectUserByUserName(@PathVariable String username) {
        if (StringUtil.isNullOrEmpty(username)) {
            return Result.ok("系统异常，获取用户名失败");
        }
        User one = userService.selectUserByUserName(username);
        return null != one ? Result.ok(one) : Result.fail();
    }

    /**
     * 微信小程序端功能登录界面   再LoginFilter页面放行登录页面
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/xgLogin")
    public Result xgLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password) {

        if (StringUtil.isNullOrEmpty(username) || StringUtil.isNullOrEmpty(password)) {
            return Result.fail("用户名或者密码不能为空");
        }

        User user = userService.getUserInformation(username);

        if (user.getUsername() == null || user.getPassword() == null) {
            return Result.fail("用户名或密码错误");
        }

        if (!user.getPassword().equals(password)) {
            return Result.fail("用户密码错误");
        }

        if (!user.getAuthority().equals(1)) {
            return Result.fail("用户权限错误");
        }

        return Result.ok(user);
    }
    /**
     * 无效返回  ？？？
     * @param userId
     * @return
     */
    @GetMapping("/selectRWPoint/{userId}")
    public Result selectRWPoint(@PathVariable Integer userId) {
        List<TaskPoint> taskPoints = new ArrayList<>();
        List<Integer> pointIds = taskPointService.findPointIds(userId);
        for (int i=0;i<pointIds.size();i++){
            Integer ii = pointIds.get(i);
            TaskPoint taskPoint = taskPointService.selectPointById(ii);
//            int state = taskPointService.selectUserRWPointState(userId, ii);
            int state = 0;
            String state11 = "未完成";
            if(state==0){
                state11 = "未完成";
            }else {
                state11 = "已完成";
            }
            Map<String,Object> param = new HashMap<>();
            //0-未完成  1-已完成
            param.put("state",state11);
            taskPoint.setParam(param);
            taskPoints.add(taskPoint);
        }
        return Result.ok(taskPoints);
    }


    /**
     *  ???
     * @param userId
     * @param startTime
     * @param overTime
     * @return
     */
    @GetMapping("/selectOneXGHistory")
    public Result selectXGHistory(@RequestParam(value = "userId") Integer userId,
                                  @RequestParam(value = "startTime") String startTime,
                                  @RequestParam(value = "overTime") String overTime){
        String s1 = "userlocus:" + userId + ":" + startTime + ":" + overTime;
        List<String> list = redisTemplate.opsForList().range(s1,0,-1);
        List<Map<String, Object>> list1 = new ArrayList<>();

        for (int j=0;j<list.size();j++){
            System.out.println(list.get(j));
            Object latitudeX = redisTemplate.opsForHash().get(list.get(j), "latitudeX");
            Object longitudeY = redisTemplate.opsForHash().get(list.get(j), "longitudeY");
            String o = (String) list.get(j);
            String time = o.replace("location:" + userId + ":", "");
            Map<String, Object> m1 = new HashMap<>();
            m1.put("latitudeX", latitudeX);
            m1.put("longitudeY", longitudeY);
            m1.put("time", time);
            list1.add(m1);
        }
        return Result.ok(list1);
    }

    @GetMapping("/selectXGUserStatus/{userId}")
    public Result selectXGUserStatus(@PathVariable Integer userId) {
        int i = userService.selectXGUserStatus(userId);
        return Result.ok(i);
    }

    @PostMapping("/updateXGUser")
    public Result updateXGUser(@RequestParam("userId")Integer userId,
                               @RequestParam("username")String username,
                               @RequestParam("realName")String realName,
                               @RequestParam("sex")int sex,
                               @RequestParam("tel")String tel,
                               @RequestParam("email")String email) {
        User user = new User(userId,username,realName,sex,tel,email);
        boolean b = userService.updateById(user);
        if (b){
            User user1 = userService.selectUserById(String.valueOf(userId));
            return Result.ok(user1);
        }
        return Result.fail();
    }

    @PostMapping("/weixinSendImage")
    public Result fileUpload(@RequestParam("file") MultipartFile multipartFile, Integer userId) {
        Result result = new Result();
        FileUtil fu = new FileUtil();
        // 获取图片的名字, 使用UUID重命名文件
        String fileName = UUID.randomUUID().toString().replace("-", "") + "." + fu.getSuffix(multipartFile.getOriginalFilename());
        if (!multipartFile.isEmpty()) {
            String savePath = uploadPath;
            try {
                FileUtil.uploadFile(multipartFile.getBytes(), savePath, fileName);
                String path = "http://8.130.69.175:8080/api/worker/Info/" + fileName;
                boolean b = userService.xgUpdatePhotoUrl(userId, path);
                if (b){
                    result.setCode(200);
                    result.setMessage(path);
                    return result;
                }
                return Result.fail();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Result.fail();
    }
    @GetMapping("/weixinShowImage/{userId}")
    public Result showImage(@PathVariable String userId) {
        User user = userService.selectUserById(userId);
        return Result.ok(user.getImg());
    }

    @PostMapping("/selectAll")
    public Result showUsers(){
        ArrayList<User> users = userService.selectAllUsers();
        return Result.ok(users);
    }

    @GetMapping("/query")
    public TableMap queryXgpq(){
        Page<Xgpq> xgpqPage = xgpqService.pageAll(0, 10);
        TableMap tableMap = new TableMap();
        tableMap.setData(xgpqPage.getRecords());
        tableMap.setCount(xgpqPage.getTotal());
        return tableMap;
    }

}
